<template>
    <div class="imgs-content-box" style="height: 100%;">
        <div v-if="showImgList" class="imgs-outer-box">
            <el-upload
                class="upload-demo"
                action="/h5/app/upload"
                :accept="accept"
                :on-success="getImageList"
                :data="{source_type: 1}"
                :with-credentials="true"
                :show-file-list="false">
                <div class="add-img">添加图片</div>
            </el-upload>
            <ul class="img-inner-box" v-if="imageList.length > 0">
                <li class="img-li"
                    v-for="(item, i) in imageList"
                    :key="i"
                    :style="`background-image: url(${item.path});`"
                    :class="{'select-img': item.selected}"
                    @click="selectImg(i);">
                    <i :class="{'checked-icon el-icon-check': item.selected}"/>
                    <i class="del-btn el-icon-circle-close" @click.stop="delImg(item.id, i);"/>
                </li>
            </ul>
            <footer class="footer" v-if="imageList.length > 0">
                <div class="footer-btns">
                    <!--<el-button size="mini">放弃修改</el-button>-->
                    <el-button
                        size="mini"
                        type="primary"
                        @click="confirmImgs();">
                        确 认
                    </el-button>
                </div>
            </footer>
        </div>
        <div v-else class="selected-img-box">
            <div class="img-btn">
                <el-tooltip class="item"
                            v-if="total>0"
                            effect="dark"
                            content="删除当前图片"
                            placement="top-start">
                    <font class="change-img-icon el-icon-remove"
                          @click="removeImage();"/>
                </el-tooltip>
                <el-pagination
                    background
                    v-if="total>0"
                    :page-size="1"
                    :pager-count="5"
                    :current-page.sync="currentImgIndex"
                    layout="pager"
                    :total="total">
                </el-pagination>
                <el-tooltip class="item"
                            effect="dark"
                            content="添加图片"
                            placement="top-start">
                    <font class="change-img-icon el-icon-circle-plus"
                          @click="showImgList=true;"/>
                </el-tooltip>
            </div>
            <div class="selected-img" :style="`background-image: url(${currentImg})`">
                <div class="imgs-edit">
                    <div class="edit-pic change-pic" @click="replaceImg();">替换</div>
                    <div class="edit-pic del-pic" @click="removeImage();">删除</div>
                    <div class="edit-pic cut-pic" @click="beforeCut">裁剪</div>
                </div>
            </div>
            <div class="auto-play">
                <el-checkbox v-model="content.autoplay">自动播放</el-checkbox>
            </div>
            <div class="imgs-tip">
                <p class="tip-header">提示</p>
                <p class="tip-content">1、可支持的图片格式为.jpg，.jpeg，.webp，.png，.gif</p>
                <p class="tip-content">2、建议图片大小控制在1M内</p>
                <p class="tip-content">3、建议图片宽度在320至640像素之间</p>
            </div>
        </div>
        <el-dialog
            title="裁剪图片"
            width="30%"
            :visible.sync="dialogVisible"
            :before-close="handleClose">
            <Cropper ref="cropper"
                     :zoomable="option.zoomable"
                     :src="currentImg"/>
            <span slot="footer" class="dialog-footer">
                <el-button
                    size="mini"
                    @click="dialogVisible = false;">
                    取 消
                </el-button>
                <el-button
                    size="mini"
                    type="primary"
                    @click="onCutImg();">
                    确 定
                </el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import Cropper from 'vue-cropperjs';
    import {getImgList, delImg, uploadBase64} from '@/api/edit';
    import {prompt} from '@/utils/edit';

    export default {
        name: 'ImagesContent',
        props: {
            content: {
                type: Object,
                default: _ => {
                    return {
                        // currentIndex: 0,
                        // Content.vue中暂时没用
                        height: 160,
                        autoplay: false,
                        urls: []
                    };
                }
            }
        },
        components: {
            Cropper
        },
        data() {
            return {
                showImgList: true,
                dialogVisible: false,
                currentImgIndex: 1,
                // 替换与否的标志
                isReplace: false,
                params: {
                    source_id: '',
                    img_width: 0,
                    img_height: 0,
                    img_base64: ''
                },
                option: {
                    // 图片是否允许滚轮缩放
                    zoomable: true,
                    // 是否默认生成截图框
                    autoCrop: true,
                    // 裁剪比例 0(表示自由设置裁剪尺寸)
                    aspectRatio: 16 / 9
                },
                accept: 'image/jpg, image/jpeg, image/webp, image/png, image/gif',
                imageList: []
            };
        },
        computed: {
            currentImg() {
                if (this.content.urls.length > 0) {
                    return this.content.urls[this.currentImgIndex - 1].path;
                }
                return './static/img/page/default.png';
            },
            total() {
                return this.content.urls.length;
            }
        },
        created() {
            this.getImageList();
        },
        methods: {
            getImageList(response, file, fileList) {
                if (response && response.code !== 0) {
                    prompt(this, 'error', response.message);
                }
                getImgList().then(res => {
                    if (res.code === 0) {
                        let nData = res.data;
                        for (let item of nData) {
                            item.selected = false;
                        }
                        this.imageList = nData.reverse();
                        this.scanImg();
                    }
                });
            },
            confirmImgs() {
                this.isReplace = false;
                this.showImgList = false;
            },
            delImg(source_id, index) {
                delImg(source_id).then(res => {
                    if (res.code === 0) {
                        this.imageList.splice(index, 1);
                    }
                });
            },
            selectImg(index) {
                let urls = this.content.urls;
                let flag = false;

                /*
                * 判断当前选择的图片是否已经被选过了
                * */
                for (let i = 0; i < urls.length; i++) {
                    if (urls[i].id === this.imageList[index].id) {
                        flag = true;
                        break;
                    }
                }

                if (flag) {
                    // 当前图片被选中
                    return;
                } else {
                    // 当前图片没有被选中
                    // if替换 或 else添加图片
                    if (this.isReplace) {
                        urls.splice(this.currentImgIndex - 1, 1, this.imageList[index]);
                        this.scanImg();

                        this.content.height = 0;
                        for (let item of this.content.urls) {
                            this.getImgHeight(item.path);
                        }
                    } else if (urls.length < 6) {
                        urls.push(this.imageList[index]);
                        this.getImgHeight(this.imageList[index].path);
                        this.imageList[index].selected = true;
                    } else {
                        prompt(this, 'info', '组图最多包含6张图片');
                        return;
                    }
                }
            },
            replaceImg() {
                this.isReplace = true;
                this.showImgList = true;
            },
            scanImg() {
                let urls = this.content.urls;
                for (let item of this.imageList) {
                    let flag = false;
                    for (let url of urls) {
                        if (item.id === url.id) {
                            flag = true;
                        }
                    }
                    item.selected = flag;
                }
            },
            removeImage() {
                this.content.urls.splice(this.currentImgIndex - 1, 1);
                this.currentImgIndex = 1;
                this.compareImg();

                this.content.height = 0;
                for (let item of this.content.urls) {
                    this.getImgHeight(item.path);
                }
            },
            compareImg() {
                let urls = this.content.urls;
                let urlArr = [];

                for (let i = 0; i < urls.length; i++) {
                    urlArr[i] = urls[i].path;
                }

                for (let item of this.imageList) {
                    if (urlArr.indexOf(item.path) > -1) {
                        item.selected = true;
                    } else {
                        item.selected = false;
                    }
                }
            },
            beforeCut() {
                if (this.currentImg) {
                    this.$refs.cropper && this.$refs.cropper.replace(this.currentImg);
                    this.dialogVisible = true;
                } else {
                    prompt(this, 'warning', '请先选择一张图片');
                }
            },
            onCutImg() {
                this.params.img_base64 = this.$refs.cropper.getCroppedCanvas().toDataURL();
                let _img = new Image();
                _img.addEventListener('load', _ => {
                    this.params.img_width = _img.naturalWidth;
                    this.params.img_height = _img.naturalHeight;
                    this.submitBase64();
                }, false);
                _img.src = this.content.urls[this.currentImgIndex - 1].path;
            },
            submitBase64() {
                let i = this.currentImgIndex - 1;
                this.params.source_id = this.content.urls[i].id;
                uploadBase64(this.params).then(res => {
                    if (res.code === 0) {
                        this.content.urls[i].path = res.data.url;
                        this.getImageList();
                        this.dialogVisible = false;
                    }
                });
            },
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {
                    });
            },
            getImgHeight(path) {
                let k = new Date().getTime();
                let _imgs = {};

                _imgs[`_img${k}`] = new Image();
                _imgs[`_img${k}`].addEventListener('load', _ => {
                    this.content.height = Math.max(this.content.height, (375 * _imgs[`_img${k}`].naturalHeight) / _imgs[`_img${k}`].naturalWidth);
                }, false);
                _imgs[`_img${k}`].src = path;
            }
        }
    }
</script>

<style scoped lang="scss">
    @import "../../../styles/mixin";

    $color-409EFF: #409EFF;
    @mixin ul-li {
        ul, li {
            margin: 0;
            padding: 0;
            list-style: none;
        }
    }

    .imgs-content-box {
        width: 100%;
        @include ul-li;
        @include scroll-bar-transparent;

        .imgs-outer-box {
            position: relative;

            .add-img {
                height: 30px;
                line-height: 30px;
                text-align: center;
                border-radius: 15px;
                cursor: pointer;
                font-weight: 600;
                color: #409EFF;
                border: 1px solid #409EFF;

                &:hover {
                    color: #ffffff;
                    background-color: #409EFF;
                }
            }
            .img-inner-box {
                padding-top: 10px;
                display: flex;
                flex-wrap: wrap;
                justify-content: space-between;

                li.img-li {
                    width: 49%;
                    height: 90px;
                    position: relative;
                    cursor: pointer;
                    margin-bottom: 10px;
                    border: 1px solid #cccccc;
                    box-sizing: border-box;
                    background-position: center;
                    background-repeat: no-repeat;
                    background-size: contain;

                    .del-btn {
                        font-size: 16px;
                        display: none;
                        cursor: pointer;
                    }
                    &:hover .del-btn {
                        display: block;
                        float: right;
                    }
                }
                .select-img {
                    border-color: $color-409EFF;

                    .checked-icon {
                        width: 16px;
                        height: 14px;
                        text-align: center;
                        border-radius: 2px;
                        font-weight: bold;
                        display: block;
                        color: #fff;
                        background-color: $color-409EFF;

                        position: absolute;
                        right: -1px;
                        bottom: -1px;
                    }
                }
            }
            .footer {
                width: 100%;
                height: 50px;
                border-top: 3px solid #cccccc;
                position: absolute;

                display: flex;
                justify-content: flex-end;
                align-items: center;
            }
        }
        .selected-img-box {
            .img-btn {
                padding-bottom: 20px;
                display: flex;
                align-items: center;

                .change-img-icon {
                    cursor: pointer;
                    font-size: 18px;
                    color: rgba(#000000, .7);

                    &:hover {
                        color: $color-409EFF;
                    }
                }
            }
            .selected-img {
                position: relative;
                height: 160px;
                user-select: none;
                background-repeat: no-repeat;
                background-size: contain;
                background-position: center;
                border: 1px dashed rgba(#000000, .5);

                .imgs-edit {
                    width: 100%;
                    position: absolute;
                    bottom: 0;
                    cursor: pointer;
                    display: flex;
                    color: #ffffff;
                    font-weight: bold;
                    background: rgba(0, 0, 0, .5);

                    .edit-pic {
                        flex: 1;
                        height: 26px;
                        text-align: center;
                        line-height: 26px;

                        &:hover {
                            background-color: $color-409EFF;
                        }
                    }
                }
            }
            .auto-play {
                padding-top: 20px;
            }
        }
        .imgs-tip {
            padding-top: 20px;

            p {
                font-size: 13px;
                color: #BABABA;
                margin: 5px 0;
            }
            .tip-header {
                color: #000000;
            }
        }
    }
</style>
<style lang="scss">
    .imgs-content-box {
        .imgs-outer-box {
            .upload-demo {
                width: 100%;
                .el-upload.el-upload--text {
                    width: 100%;
                }
            }
        }
        .selected-img-box {
            .img-btn {
                .number,
                .el-icon.more.el-icon-more,
                .el-icon.more.el-icon-d-arrow-left,
                .el-icon.more.el-icon-d-arrow-right {
                    min-width: 24px;
                    height: 24px;
                    line-height: 24px;
                }
                .el-pager .more::before {
                    line-height: 24px;
                }
            }
        }
    }
</style>
